package com.google.gac.masai.getit;

import java.io.File;
import java.io.FilePermission;
import java.util.ArrayList;

import com.dropbox.client.DropboxAPI;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;


// parameters progress result
public class LoginCredAsync extends AsyncTask<Void, String, DropBox> {

	private Context  mActitivty;
	 
	
	
	
	private String username;
	private String password; 
	private boolean delete;
	
	public String[] StringParams; 
	
	/**
	 * Connects to dropbox using the username and password provided
	 * @param activity - the activity where the login operation will run under
	 * @param username - username to connect to dropbox
	 * @param passsword - password to connect to dropbox
	 */
	public LoginCredAsync (Context activity, String username, String password){
		
		this.username = username;
		this.password = password;
		
		mActitivty = activity;
		
		
		
	}
	
	// Runs on main thread.
    @Override
    protected void onProgressUpdate(String... msgs) {
        if (msgs[0] != null) {
            showToast(msgs[0]);
        }
    }
	
	
    @Override
	protected DropBox doInBackground(Void... params) {
		
    	publishProgress("Connecting to DropBox. Please be patient...");
    	DropBox db = new DropBox(username,password); // connect to dropbox
    	
    	return db; 
    	
	}
	//
    

	@Override
	protected void onPostExecute(DropBox db) {
		// TODO Auto-generated method stub
		super.onPostExecute(db);
		
		// See if login failed
		if(!db.isConnected()){	
			showToast("DropBox Login failed. Please make sure that you correctly entered your credentials" +
					" and that you have access to the internet and try again. ");
			return; // stop here
		}
		
		showToast("Successfully Connected Dropbox Account");
		String[] keys = db.getStoredTokens();
		
		SharedPreferences data = mActitivty.getSharedPreferences(DropBox.CRED, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = data.edit(); // create new shared pref file if one didn't exist before
        
        // Save access tokens
        editor.putString("ACCESS_KEY", keys[0]);
        editor.putString("ACCESS_SECRET", keys[1]);
        editor.putString("DROPBOX_USER", username); // save the email id associated with these access tokens
        editor.commit(); // save the key-values pair data
        
		
		log("Connecting to DropBox using username and password succeeded");
		log("Successfully Saved DropBox Credentials");
		//showToast("Successfully Saved DropBox Credentials");
	
		return ; 
	}

	
	
	
	public void log(String msg){
		
		Log.d("DROPBOX", msg);
	}
	
	
	public void showToast(String msg) {
		Toast error = Toast.makeText(mActitivty, msg, Toast.LENGTH_LONG);
        error.show();
    }

	
	
}
